#!/bin/bash

# 部署脚本 - 支持Git代码拉取和Token认证
set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color

# 项目信息
PROJECT_NAME="scpf-platform-admin"
IMAGE_NAME="scpf-platform-admin"
TAG=${1:-latest}

# Git配置
GIT_REPO_URL=${GIT_REPO_URL:-"https://gitee.com/xsfcjy/scpf-platform-admin.git"}
GIT_BRANCH=${GIT_BRANCH:-"main"}
GIT_TOKEN=${GIT_TOKEN:-"e962dcccdb1e3384645c7c5c4c1e47c7"}
GIT_USERNAME=${GIT_USERNAME:-"xsfcjy"}

# 工作目录
WORK_DIR=${WORK_DIR:-"/data/source/scpf/worksapce"}
BACKUP_DIR=${BACKUP_DIR:-"/data/source/scpf/backup"}

# 日志文件
LOG_FILE="/data/source/scpf/logs/scpf-deploy-$(date +%Y%m%d_%H%M%S).log"

# 日志函数
log() {
    echo -e "$1" | tee -a "$LOG_FILE"
}

# 错误处理函数
error_exit() {
    log "${RED}❌ 错误: $1${NC}"
    exit 1
}

# 检查必需的工具
check_requirements() {
    log "${BLUE}🔍 检查部署环境...${NC}"

    # 检查Git
    if ! command -v git &> /dev/null; then
        error_exit "Git 未安装"
    fi

    # 检查Docker
    if ! docker info > /dev/null 2>&1; then
        error_exit "Docker 未运行或无法访问"
    fi

    # 检查docker-compose
    if ! command -v docker-compose &> /dev/null; then
        error_exit "docker-compose 未安装"
    fi

    # 检查Git Token
    if [ -z "$GIT_TOKEN" ]; then
        error_exit "请设置 GIT_TOKEN 环境变量"
    fi

    log "${GREEN}✅ 环境检查通过${NC}"
}

# 配置Git认证
setup_git_auth() {
    log "${BLUE}🔧 配置Git认证...${NC}"

    # 配置Git用户信息
    git config --global user.name "$GIT_USERNAME" || true
    git config --global user.email "$GIT_USERNAME@example.com" || true

    # 配置Git凭证存储
    git config --global credential.helper store || true

    # 创建Git凭证文件
    echo "https://oauth2:${GIT_TOKEN}@gitee.com" > ~/.git-credentials

    log "${GREEN}✅ Git认证配置完成${NC}"
}

# 备份当前代码
backup_current_code() {
    if [ -d "$WORK_DIR" ]; then
        log "${YELLOW}📦 备份当前代码...${NC}"
        mkdir -p "$BACKUP_DIR"
        cp -r "$WORK_DIR" "$BACKUP_DIR/scpf-backup-$(date +%Y%m%d_%H%M%S)" || true
        log "${GREEN}✅ 代码备份完成${NC}"
    fi
}

# 拉取最新代码
pull_latest_code() {
    log "${BLUE}📥 拉取最新代码...${NC}"

    # 创建或清理工作目录
    if [ -d "$WORK_DIR" ]; then
        log "${YELLOW}清理工作目录...${NC}"
        rm -rf "$WORK_DIR"
    fi

    mkdir -p "$WORK_DIR"
    cd "$WORK_DIR"

    # 克隆仓库
    log "${YELLOW}克隆仓库: $GIT_REPO_URL${NC}"
    if git clone --depth 1 --branch "$GIT_BRANCH" "$GIT_REPO_URL" .; then
        log "${GREEN}✅ 代码拉取成功${NC}"

        # 显示提交信息
        COMMIT_HASH=$(git rev-parse --short HEAD)
        COMMIT_MSG=$(git log -1 --pretty=format:"%s")
        log "${PURPLE}📝 最新提交: $COMMIT_HASH - $COMMIT_MSG${NC}"
    else
        error_exit "代码拉取失败"
    fi
}

# 检查代码变更
check_code_changes() {
    log "${BLUE}🔍 检查代码变更...${NC}"

    if [ -d "$BACKUP_DIR" ] && [ -d "$WORK_DIR" ]; then
        # 比较文件变更
        if diff -r "$BACKUP_DIR" "$WORK_DIR" > /dev/null 2>&1; then
            log "${YELLOW}⚠️  代码无变更，是否继续部署? (y/N)${NC}"
            read -r response
            if [[ ! "$response" =~ ^[Yy]$ ]]; then
                log "${YELLOW}部署已取消${NC}"
                exit 0
            fi
        else
            log "${GREEN}✅ 检测到代码变更${NC}"
        fi
    fi
}

# 构建Docker镜像
build_docker_image() {
    log "${BLUE}🐳 构建Docker镜像...${NC}"

    cd "$WORK_DIR"

    # 检查Dockerfile是否存在
    if [ ! -f "Dockerfile" ]; then
        error_exit "Dockerfile 不存在"
    fi

    # 构建镜像
    log "${YELLOW}构建镜像: $IMAGE_NAME:$TAG${NC}"
    if docker build -t "$IMAGE_NAME:$TAG" .; then
        log "${GREEN}✅ Docker镜像构建成功${NC}"
    else
        error_exit "Docker镜像构建失败"
    fi
}

# 部署服务
deploy_service() {
    log "${BLUE}🚀 部署服务...${NC}"

    cd "$WORK_DIR"

    # 停止并删除旧容器
    log "${YELLOW}停止旧容器...${NC}"
    docker-compose down --remove-orphans 2>/dev/null || true

    # 强制删除同名容器（如果存在）
    log "${YELLOW}清理同名容器...${NC}"
    docker rm -f scpf-platform-admin 2>/dev/null || true

    # 清理旧镜像
    log "${YELLOW}清理旧镜像...${NC}"
    docker image prune -f

    # 构建并启动服务
    log "${GREEN}构建并启动服务...${NC}"
    if docker-compose up -d --build; then
        log "${GREEN}✅ 服务启动成功${NC}"
    else
        error_exit "服务启动失败"
    fi
}

# 健康检查
health_check() {
    log "${BLUE}🏥 执行健康检查...${NC}"

    # 等待服务启动
    log "${YELLOW}等待服务启动...${NC}"
    sleep 15

    # 检查容器状态
    if docker-compose ps | grep -q "Up"; then
        log "${GREEN}✅ 容器运行正常${NC}"
    else
        error_exit "容器启动失败"
    fi

    # HTTP健康检查
    for i in {1..10}; do
        if curl -f http://localhost:3002/ > /dev/null 2>&1; then
            log "${GREEN}✅ HTTP健康检查通过${NC}"
            break
        else
            log "${YELLOW}等待服务就绪... (${i}/10)${NC}"
            sleep 3
        fi

        if [ $i -eq 10 ]; then
            error_exit "健康检查失败"
        fi
    done
}

# 显示部署信息
show_deployment_info() {
    log "${GREEN}🎉 部署完成!${NC}"
    log "${BLUE}================================${NC}"
    log "${YELLOW}服务信息:${NC}"
    log "  项目名称: $PROJECT_NAME"
    log "  镜像标签: $TAG"
    log "  访问地址: http://localhost:3002"
    log "  工作目录: $WORK_DIR"
    log "  日志文件: $LOG_FILE"
    log ""
    log "${YELLOW}常用命令:${NC}"
    log "  查看日志: docker-compose logs -f"
    log "  停止服务: docker-compose down"
    log "  重启服务: docker-compose restart"
    log "  进入容器: docker-compose exec scpf-platform-admin sh"
    log "${BLUE}================================${NC}"
}

# 清理函数
cleanup() {
    log "${YELLOW}🧹 清理临时文件...${NC}"

    # 清理Git凭证
    rm -f ~/.git-credentials

    # 清理备份（保留最近3个）
    if [ -d "$BACKUP_DIR" ]; then
        cd "$BACKUP_DIR"
        ls -t | tail -n +4 | xargs -r rm -rf
    fi

    log "${GREEN}✅ 清理完成${NC}"
}

# 主函数
main() {
    log "${GREEN}🚀 开始部署 $PROJECT_NAME...${NC}"
    log "${YELLOW}镜像标签: $TAG${NC}"
    log "${YELLOW}Git分支: $GIT_BRANCH${NC}"
    log "${YELLOW}日志文件: $LOG_FILE${NC}"

    # 执行部署步骤
    check_requirements
    setup_git_auth
    backup_current_code
    pull_latest_code
    check_code_changes
    build_docker_image
    deploy_service
    health_check
    show_deployment_info
    cleanup

    log "${GREEN}🎉 部署流程完成!${NC}"
}

# 信号处理
trap 'log "${RED}⚠️  部署被中断${NC}"; cleanup; exit 1' INT TERM

# 执行主函数
main "$@"
